package com.gets.web.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gets.web.model.ImageSetListEntity;
import com.gets.web.model.ImageSetEntity;
import org.jsoup.Jsoup;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by me on 2016/8/29.
 */
public class GetImage {
    public static void main(String args[]) throws IOException {
        // 参数依次为 AppId、AppKey、MasterKey
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    getImage("Cosplay",24);
                    getImage("丝袜",21);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                try {
                    getImage("运动",13);
                    getImage("动漫",17);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                try {
                    getImage("模特",16);
                    getImage("比基尼",18);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread3.start();
        Thread thread4 = new Thread(new Runnable() {
            public void run() {
                try {
                    getImage("内衣",48);
                    getImage("制服",15);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread4.start();
    }

    public static void getImage(String category,int imgNum) throws IOException {
        String categorylist = "http://114.215.137.225/categorylist?category="+category+"&p=";
        String imageSet = "http://114.215.137.225/imageSet?id=";
        String img = "http://114.215.137.225/img/";
        String userAgent = "Mozilla/5.0 (Linux; U; Android 4.4.4; zh-cn; MI 4LTE Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 XiaoMi/MiuiBrowser/2.1.1";
        for (int i = 0; i <= imgNum; i++) {
            System.out.println(category+"="+String.valueOf(i));
            String imageSetInfos = Jsoup.connect(categorylist + i).userAgent(userAgent)
                    .timeout(12000).ignoreContentType(true).get().body().text();
            ArrayList<ImageSetListEntity> imageSetInfoEntities = JSON.parseObject(imageSetInfos, new TypeReference<ArrayList<ImageSetListEntity>>() {
            });
            for (ImageSetListEntity imageSetInfoEntity : imageSetInfoEntities) {
               /* Jsoup.connect("http://127.0.0.1:8080/insertImageSetList?id=" + imageSetInfoEntity.getId()
                        + "&category=" + imageSetInfoEntity.getCategory()
                        + "&cover_url=" + imageSetInfoEntity.getCover_url()
                        + "&create_time=" + imageSetInfoEntity.getCreate_time()
                        + "&label=" + imageSetInfoEntity.getLabel()
                        + "&title=" + imageSetInfoEntity.getTitle()
                        + "&comment_count=" + imageSetInfoEntity.getComment_count()
                        + "&img_count=" + imageSetInfoEntity.getImg_count()
                        + "&like_count=" + imageSetInfoEntity.getLike_count()
                ).userAgent(userAgent)
                        .timeout(12000).ignoreContentType(true).get().body().text();*/
                MysqlHelper mysqlHelper=new MysqlHelper();
                try {
                    mysqlHelper.addDeleteModify("insert into image_set_list values("
                            + imageSetInfoEntity.getId() + ",'"
                            + imageSetInfoEntity.getCategory() + "',"
                            + imageSetInfoEntity.getComment_count() + ",'"
                            + imageSetInfoEntity.getCover_url() + "','"
                            + imageSetInfoEntity.getCreate_time() + "',"
                            + imageSetInfoEntity.getImg_count() + ",'"
                            + imageSetInfoEntity.getLabel() + "',"
                            + imageSetInfoEntity.getLike_count() + ",'"
                            + imageSetInfoEntity.getTitle() + "')",null);
                } catch (SQLException e) {
                    e.printStackTrace();
                }finally {
                    mysqlHelper.closeconnection();
                }
              //  dbHelper.insert();
                String imageSets = Jsoup.connect(imageSet + imageSetInfoEntity.getId()).ignoreContentType(true).userAgent(userAgent)
                        .timeout(12000).get().body().text();
                ArrayList<ImageSetEntity> imageSetEntities = JSON.parseObject(imageSets, new TypeReference<ArrayList<ImageSetEntity>>() {
                });
                for (ImageSetEntity imageSetEntity : imageSetEntities) {
                    imageSetEntity.setUrl(imageSetEntity.getUrl().replace("%5C", "/"));
                    imageSetEntity.setUrl(imageSetEntity.getUrl().replace("\\", "/"));
                  /*  Jsoup.connect("http://127.0.0.1:8080/insertImageSet?id=" + imageSetEntity.getId()
                            + "&all_images_id=" + imageSetEntity.getAll_images_id()
                            + "&url=" + imageSetEntity.getUrl()
                    ).userAgent(userAgent)
                            .timeout(12000).ignoreContentType(true).get().body().text();*/
                   MysqlHelper mysqlHelper1=new MysqlHelper();
                    try {
                        mysqlHelper1.addDeleteModify("insert into image_set values("+imageSetEntity.getId()+","+imageSetEntity.getAll_images_id()+",'"+imageSetEntity.getUrl()+"')",null);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }finally {
                        mysqlHelper1.closeconnection();
                    }
                    String imageSetUrlSet[] = imageSetEntity.getUrl().split("/");
                    File dirFile = new File("C:\\app\\img\\" + imageSetUrlSet[0] + "\\");
                    if (!dirFile.exists()) {
                        dirFile.mkdir();
                    }
                    File dirIdFile = new File("C:\\app\\img\\" + imageSetUrlSet[0] + "\\" + imageSetInfoEntity.getId());
                    if (!dirIdFile.exists()) {
                        dirIdFile.mkdir();
                    }
                    String imageSetFileName = imageSetUrlSet[imageSetUrlSet.length - 1];
                    getImageFromUrl(img + imageSetEntity.getUrl(), "C:\\app\\img\\" + imageSetUrlSet[0] + "\\" + imageSetInfoEntity.getId(), imageSetFileName);
                }
            }
        }
    }

    public static void getImageFromUrl(String url, String dirName, String fileName) {
        byte[] btImg = getImageFromNetByUrl(url);
        if (null != btImg && btImg.length > 0) {
            //   System.out.println("读取到：" + btImg.length + " 字节");
            writeImageToDisk(btImg, dirName, fileName);
        } else {
            System.out.println("没有从该连接获得内容");
        }
    }

    /**
     * 将图片写入到磁盘
     *
     * @param img      图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String dirName, String fileName) {
        try {
            File file = new File(dirName + "\\" + fileName);
            if (file.exists()) return;
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("图片" + fileName + "已经写入到C盘");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
